from collections import defaultdict
f=open('C:/Users/N551/Desktop/tan-data2.txt','r')
result=list()
num=0
readlines=f.readlines()
for line in readlines:
    if line.find('AppOpenAction'):#13
        num+=1
Trainnum=int(num*0.8)#前80%用来训练后20%用来测试
testnum=num-Trainnum
print(Trainnum,testnum)
f.close()
predict=list()
#print (line[line.find('AppOpenAction')+14:-2])
#result.append(line)
#i=0
#for temp in result:
#    print (temp)
#    i+=1
#   if i>2 :
#        f.close()
#        exit()
#p(b|a)=p(ab)/p(a) p(a)一样其实就是看ab一起发生的次数取多的
def lu(a,Trainnum,appnum):
    pa_num=0
    p_ab=defaultdict(int)
    thx=0
    global predict
    for line in readlines:
        if thx>Trainnum :
            break
        thx+=1
        if a in line:
            pa_num+=1
            if line.find('AppOpenAction'):#13
               key=line[line.find('AppOpenAction')+14:-2]
               p_ab[key]+=1
    #pa=pa_num/Trainnum
    res= sorted(p_ab.items(), key=lambda d:d[1], reverse = True)
    #print(res)
    anum=1
    for key,value in res:
        if anum>appnum: 
            break
        predict.append(key)
        anum+=1
    #print(predict)
    return predict

def test():
    right=[0]*5
    er=0
    ac=[0]*5
    global predict
    for line in readlines[Trainnum:-1]:    
        predict=list()
        for temp in range(0,5):
            predict=list()
            predict=lu(line[0:line.find('+')],Trainnum,temp+1)
            print(predict)
            for pre in predict:
                #print(key)
                if pre==line[line.find('AppOpenAction')+14:-2]:
                    right[temp]+=1
                    break
    for temp in range(0,5):
        ac[temp]=right[temp]/testnum
        print('AC%s=%s'%(temp+1,ac[temp]))
    #ac=right/testnum
    #print('AC=%s'%ac)

test()